//================================================================================================================================
//
// Copyright (c) 2015-2022 VisionStar Information Technology (Shanghai) Co., Ltd. All Rights Reserved.
// EasyAR is the registered trademark or trademark of VisionStar Information Technology (Shanghai) Co., Ltd in China
// and other countries for the augmented reality technology developed by VisionStar Information Technology (Shanghai) Co., Ltd.
//
//================================================================================================================================

package com.lyc.easyartranslator;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.lyc.easyar.GLView;
import com.lyc.easyar.PathCallback;
import com.lyc.easyar.ShakeDetector;
import com.lyc.easyar.TraceCallback;

import java.util.HashMap;

import cn.easyar.Engine;
import cn.easyar.ImageTracker;

public class ARActivity extends Activity
{
    /*
     * Steps to create the key for this sample:
     *  1. login www.easyar.com
     *  2. create app with
     *      Name: HelloARCustomCamera
     *      Package Name: cn.easyar.samples.helloarcustomcamera
     *  3. find the created item in the list and show key
     *  4. set key string bellow
     */
    private static String key = "XmtxKlp4aTZCHlFi5iqLEl7epzN1rOk5yVdZUW5ZRwFaSUEcbkRWUSEIFEIrHhRHIx8WM2pbDBB0RwBfOUdDAG9PUDh+U2sXORATXzlGSxB+RFEWaAgYKGAIQAZ1Tk4WUk5RUSFxf185XEMBcktMB2gIGCg5SU0edl9MGm9TAC43CFIfel5EHGlHUVEhcQAEckRGHGxZAF85R0MQOXcOUXZFRgZ3T1FRIXEAAH5EURY1Y08SfE92AXpJSRp1TQBfOVlHHWhPDDB3RVcXSU9BHHxESwdyRUxRNwhRFnVZR11JT0EcaU5LHXwIDlFoT0wAfgRtEXFPQQdPWEMQcENMFDkGAAB+RFEWNXlXAX1LQRZPWEMQcENMFDkGAAB+RFEWNXlSEmlZRyBrS1YaekZvEmsIDlFoT0wAfgRvHG9DTR1PWEMQcENMFDkGAAB+RFEWNW5HHW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ZYNMT7GoCpXLFXVSVHaz3I3dAbu2AL/2BVpS5qmXY4aMNf1wPF2iJRy4UInjL+wySmLObmYYR6g3UoA5xzMLuFaY/BvHOu91t3OlYGDHgQbj5K9BO6VuW4aizA51ONtfB+CY8gmCYJ1M/ZPA0/L9/0o8hWV7gv4iNdKtO5wJLN3x/FHYZ2ZCxD4k3E6JfFPnHz0m08qQ1Z5OGESkQsjiZmn5O/wiyKOn52+FL0ir8ty7TIDW6UfmiHFNsbKiJz";
    private GLView glView;
    private Handler mHandler = new Handler(Looper.myLooper());
    private ShakeDetector shakeDetector;
    private boolean isShake;

    private Runnable takePhotoRunnable = new Runnable() {
        @Override
        public void run() {
            if(glView.isLoseTrace()){
                glView.startScanTexture();
                glView.takePhoto(true, new PathCallback() {
                    @Override
                    public void onPathBack(String path) {
                    }
                });
            }

            mHandler.removeCallbacks(takePhotoRunnable);
            mHandler.postDelayed(takePhotoRunnable, 3000);
        }
    };

    private Runnable zoomChangeRunnable = new Runnable() {
        @Override
        public void run() {
            glView.changeZoom(true);
            mHandler.removeCallbacks(zoomChangeRunnable);
            mHandler.postDelayed(zoomChangeRunnable, 1000);
        }
    };

    private ShakeDetector.OnShakeListener listener = new ShakeDetector.OnShakeListener() {
        @Override
        public void onShake() {
            mHandler.removeCallbacks(takePhotoRunnable);
            mHandler.postDelayed(takePhotoRunnable, 2000);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ar);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        if (!Engine.initialize(this, key)) {
            Log.e("HelloAR", "Initialization Failed.");
            Toast.makeText(ARActivity.this, Engine.errorMessage(), Toast.LENGTH_LONG).show();
            return;
        }

        if (!ImageTracker.isAvailable()) {
            Toast.makeText(ARActivity.this, "ImageTracker not available.", Toast.LENGTH_LONG).show();
            return;
        }
        ProgressBar progressBar = findViewById(R.id.progress_circular);

        shakeDetector = new ShakeDetector(this);

        glView = new GLView(this);
        glView.setTraceInterval(2000);
        glView.setTraceCallback(new TraceCallback() {
            @Override
            public void onLoseTrace() {
                progressBar.setVisibility(View.VISIBLE);
                mHandler.removeCallbacks(takePhotoRunnable);
                mHandler.postDelayed(takePhotoRunnable, 1000);
            }

            @Override
            public void onGetTrace() {
                progressBar.setVisibility(View.GONE);
                mHandler.removeCallbacks(takePhotoRunnable);
            }
        });

        requestCameraPermission(new PermissionCallback() {
            @Override
            public void onSuccess() {
                ((ViewGroup) findViewById(R.id.preview)).addView(
                        glView,
                        new ViewGroup.LayoutParams(
                                ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.MATCH_PARENT
                        )
                );
            }

            @Override
            public void onFailure() {
            }
        });

        //mHandler.postDelayed(zoomChangeRunnable, 2000);
    }

    private interface PermissionCallback
    {
        void onSuccess();
        void onFailure();
    }
    private HashMap<Integer, PermissionCallback> permissionCallbacks = new HashMap<Integer, PermissionCallback>();
    private int permissionRequestCodeSerial = 0;
    @TargetApi(23)
    private void requestCameraPermission(PermissionCallback callback)
    {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                int requestCode = permissionRequestCodeSerial;
                permissionRequestCodeSerial += 1;
                permissionCallbacks.put(requestCode, callback);
                requestPermissions(new String[]{Manifest.permission.CAMERA}, requestCode);
            } else {
                callback.onSuccess();
            }
        } else {
            callback.onSuccess();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
    {
        if (permissionCallbacks.containsKey(requestCode)) {
            PermissionCallback callback = permissionCallbacks.get(requestCode);
            permissionCallbacks.remove(requestCode);
            boolean executed = false;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    executed = true;
                    callback.onFailure();
                }
            }
            if (!executed) {
                callback.onSuccess();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        if (glView != null) { glView.onResume(); }
        if (shakeDetector != null){
            shakeDetector.registerOnShakeListener(listener);
            shakeDetector.start();
        }
        mHandler.postDelayed(takePhotoRunnable, 3000);
    }

    @Override
    protected void onPause()
    {
        if (glView != null) { glView.onDestroy(); }
        mHandler.removeCallbacksAndMessages(null);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (shakeDetector != null){
            shakeDetector.unregisterOnShakeListener(listener);
            shakeDetector.stop();
        }
    }
}
